package juc.jmm;
/*
* volatile 改进两阶段终止模式
* */
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
         TaskAbleTerminated.start();
         Thread.sleep(3000);
         TaskAbleTerminated.stop();
         System.out.println(Thread.currentThread());
    }
}
class TaskAbleTerminated{
    private volatile static boolean stop;
    private static Thread monitor;
    public static void start(){
        System.out.println(monitor);
        monitor = new Thread(() -> {
            while (true) {
                if (stop) {
                    System.out.println("料理后事...");
                    break;
                }
//                System.out.println("执行任务...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t1结束");
            monitor=null;//置空
        }, "t1");
        monitor.start();
//        System.out.println(monitor);
    }
    public static void stop(){
        stop=true;
        monitor.interrupt();//停止后应立即停止 而不应该再睡眠等待
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(monitor);
    }
}
